﻿using UnityEngine;
using System.Collections;
using UnityEditor;
using System;
using System.Collections.Generic;
using System.IO;

namespace HDJ.Framework.Core.Editor
{
    public class TableDataEditor
    {
        private const string FontPlayerPrefKey = "DataEditorWindow.FontKey";
        /// <summary>
        /// 加载表格
        /// </summary>
        public CallBackR<TableData, string> OnLoadTableFile;
        public Action<string, TableData> OnSaveTableData;
        public Action OnClearModuleCache;


       public  List<String> configFileNames = new List<string>();

        public TableData m_currentData;

        public EditorWindow editorWindow;
        
        private string saveConfigFilePath;
        private GridEditorGUI gridEditorGUI = null;
        public void Init(EditorWindow editorWindow,string saveConfigFilePath)
        {
            if (editorWindow)
                this.editorWindow = editorWindow;

            this.saveConfigFilePath = saveConfigFilePath;
            chooseFileName = "TestTable";
            ReInit();
        }
        private void ReInit()
        {
            InitCustomMenu();
            InitGridGUI();
            configFileNames.Clear();

            configFileNames.AddRange(PathUtils.GetDirectoryFileNames(saveConfigFilePath, new string[] { ".txt" }, false, false));

            if (!string.IsNullOrEmpty(chooseFileName) && configFileNames.Contains(chooseFileName))
                LoadData(chooseFileName);

            TableDataDrawFieldController.ReInit();
            editorWindow.Repaint();
        }
        public void OnDestroy()
        {
            PlayerPrefs.SetInt(FontPlayerPrefKey, nowButtonFontSize);
            PlayerPrefs.Save();
        }
        GridData gridData = new GridData(110,45);
        private void InitGridGUI()
        {
            gridEditorGUI = new GridEditorGUI(gridData);
            gridEditorGUI.OnDrawGridItem = OnDrawGridItem;
        }

        private void OnDrawGridItem(int x, int y, Rect rect)
        {
            helpBoxStyle.fontSize = nowButtonFontSize;

            List<TableFieldInfo> fieldInfos = new List<TableFieldInfo>(m_currentData.fieldInfos.Values);
            List<string> keys = new List<string>(m_currentData.datas.Keys);

            object value = null;
            object showValue = null;
            string showStr = "";
            string iconName = "";

            TableFieldInfo info = fieldInfos[x];
            string field = info.name;

            if (y == 0)
            {
                GUI.color = Color.yellow;

                showStr = EditorDrawGUIUtil.GetFormatName(field, info.fieldType, "red");
            }
            else if (y == 1)
            {
                GUI.color = Color.cyan;

                showStr = info.description;
            }
            else if (y == 2)
            {
                GUI.color = Color.green;

                showStr = TableTypeSupportController.Instance.ObjectValue2TableString(info.defultValue);
            }
            else
            {
                string k = keys[y - 3];
                Dictionary<string, object> values = m_currentData.datas[k];
                value = values[info.name];

                bool isDefault = TableUtils.ValueEquals(info.defultValue, value);

                if (isDefault)
                {
                    showValue = info.defultValue;
                    iconName = "lightMeter/greenLight";
                }
                else
                {
                    showValue = value;

                }
                if (TableDataDrawFieldController.HasTableDataSpecialDrawField(info.fieldType, info.tag))
                {
                    object changeValue = TableDataDrawFieldController.GetTableDataDrawField(info.fieldType, info.tag).GetShowValue(value, info);
                    if (changeValue == null)
                    {
                        iconName = "console.erroricon";
                    }
                    else
                    {
                        showValue = changeValue;
                        iconName = "preAudioLoopOn";
                    }
                }
                showStr = TableTypeSupportController.Instance.ObjectValue2TableString(showValue);

                if (!string.IsNullOrEmpty(searchValue))
                    showStr = ShowContainsChar(showStr, searchValue);

                //if (isDefault)
                //    showStr = "<color=green>" + showStr + "</color>";
            }
            GUIContent uIContent = GetGUIContent(iconName, showStr);
            if (y == 0 || y == 1 || y == 2)
            {
                GUI.Label(rect, uIContent, helpBoxStyle);
            }
            else
            {
                if (gridData. selectColumnIndexs.Contains(x))
                    GUI.color = Color.magenta;
                if (gridData. selectRowIndexs.Contains(y))
                    GUI.color = Color.cyan;

             

                if (!TableDataDrawFieldController.HasTableDataSpecialDrawField(info.fieldType, info.tag) && DrawValueEitorGUI.SupportValueType(value))
                {
                    //GUI.Box(rect, "", helpBoxStyle);
                    string k = keys[y - 3];
                    Dictionary<string, object> values = m_currentData.datas[k];
                  
                    values[info.name] = DrawValueEitorGUI.DrawValue(rect, value, helpBoxStyle);
                }
                else
                {
                    if (GUI.Button(rect, uIContent, helpBoxStyle))
                    {
                        modifiIndex = new Vector2Int(y - 3, x);
                        if (y == 0)
                        {
                            value = info.Clone();
                        }
                        else
                        {
                            //Type t = TableUtils.TableFieldType2Type(info.fieldType, info.enumType);
                            
                            string tempJson = JsonUtils.ToJson(value);
                            value = JsonUtils.FromJson(info.fieldType, tempJson);
                        }

                        GeneralDataModificationWindow.OpenWindow(editorWindow, "修改数据", value, DrawModifiValueGUI, CheckModifiValueCallBack, ModificationCompleteCallBack);
                    }
                }
            }
            GUI.color = Color.white;
        }
        private GUIContent GetGUIContent(string iconName, string text)
        {

            GUIContent cc = null;
            try
            {
                if (!string.IsNullOrEmpty(iconName))
                {
                    cc = EditorGUIUtility.IconContent(iconName.Trim());
                }
                else
                {
                    cc = new GUIContent(text);
                }
                cc.text = text;
            }
            catch (Exception e)
            {
                Debug.LogError("获取图标失败："+iconName+"\n"+ e);
                cc = new GUIContent(text);
            }

            return cc;
        }
        #region GUI

        public string OnGUI(string _chooseFileName)
        {
           
            this.chooseFileName = _chooseFileName;
            if (!string.IsNullOrEmpty(resetChooseFileName))
            {
                chooseFileName = resetChooseFileName;
                resetChooseFileName = "";
            }
            if (buttonStyle == null || helpBoxStyle == null)
            {
                buttonStyle = "Button";
                helpBoxStyle = "PreferencesSectionBox";
                helpBoxStyle.richText = true;
                helpBoxStyle.padding = new RectOffset(3,3,2,2);
                helpBoxStyle.wordWrap = true;
                
            }

            EditorDrawGUIUtil.RichTextSupport = true;
            GUILayout.Space(8);
            ChooseFile();
            if (!string.IsNullOrEmpty(chooseFileName)&& m_currentData!=null)
            {
                GUILayout.Space(9);
                GridTopFunctionGUI();
                GUILayout.Space(5);

                //  DrawTableDataGUI();
                if (editorWindow)
                {
                    gridEditorGUI.showRect = new Rect(0, 80, editorWindow.position.width, editorWindow.position.height - 80);
                  
                    gridEditorGUI.OnGUI();
                }
            }

            return chooseFileName;
        }
        public string chooseFileName = "";

        private string resetChooseFileName = "";


        void ChooseFile()
        {

            GUILayout.BeginHorizontal();
            chooseFileName = EditorDrawGUIUtil.DrawPopup("选择文件", chooseFileName, configFileNames, LoadData);
            if (m_currentData == null)
            {
                LoadData(chooseFileName);
            }

            if (GUILayout.Button("☰", "ToolbarPopup", GUILayout.Width(45)))
            {
                AddGenericMenu();
            }
            GUILayout.EndHorizontal();
        }
        private void LoadData(string fileName)
        {
            if (fileName==null|| string.IsNullOrEmpty(fileName.Trim()))
                return;
            Debug.Log("Load File :" + fileName); 
            chooseFileName = fileName;
            if (OnLoadTableFile == null)
                return;
            m_currentData = OnLoadTableFile(fileName);
            if (m_currentData == null)
                return;
            int widthCount = m_currentData.fieldInfos.Count;
            //Debug.Log(" m_currentData.TableKeys.Count :" + m_currentData.TableKeys.Count + "  withItemList.Count :" + withItemList.Count);
            if (widthCount >gridData. withItemList.Count)
            {
                int num = widthCount - gridData.withItemList.Count;
                for (int i = 0; i < num; i++)
                {
                    gridData.AddColumn();
                }
            }
            else if (widthCount < gridData.withItemList.Count)
            {
                while (widthCount < gridData.withItemList.Count)
                {
                    gridData.withItemList.RemoveAt(gridData.withItemList.Count - 1);
                }
            }
            Debug.Log(" m_currentData.TableKeys.Count :" + m_currentData.datas.Count );
            gridData.heightItemList.Clear();
            //所有的数据行+描述+默认值+空一行
            //gridData.AddRow();
            for (int i = 0; i < m_currentData.datas.Count + 3; i++)
            {
                gridData.AddRow();
            }
            for (int i = 0; i < gridData.selectRowIndexs.Count; i++)
            {
                if (gridData.selectRowIndexs[i] >= gridData.heightItemList.Count)
                {
                    gridData.selectRowIndexs.RemoveAt(i);
                    i = i - 1;
                }
            }
            for (int i = 0; i < gridData.selectColumnIndexs.Count; i++)
            {
                if (gridData.selectColumnIndexs[i] >= gridData.withItemList.Count)
                {
                    gridData.selectColumnIndexs.RemoveAt(i);
                    i = i - 1;
                }
            }

            gridData.currentShowAllRow.Clear();
            for (int i = 0; i < gridData.heightItemList.Count; i++)
            {
                gridData.currentShowAllRow.Add(i);
            }
        }

        //private List<float> withItemList = new List<float>();
        //private List<float> heightItemList = new List<float>();
        //private int minItem = 30;
        //private const int wHeight = 45;
        //private const int wWith = 110;
        //private Vector2 svPos;

        ////标记选择行
        //private List<int> selectRowIndexs = new List<int>();
        //private List<int> selectColumnIndexs = new List<int>();

        private GUIStyle buttonStyle;
        private GUIStyle helpBoxStyle;

        //private Vector2 topGridSVPos;
        //private Vector2 leftGridSVPos;

        ///// <summary>
        ///// 绘制所有格子
        ///// </summary>
        //void DrawTableDataGUI()
        //{
        //    Rect position = editorWindow.position;

        //    Rect r = new Rect(0, 90, position.width, 18);
        //    float detaH = wHeight;
        //    if (heightItemList.Count >= 3)
        //    {
        //        detaH = 0;
        //        for (int i = 0; i < 4; i++)
        //        {
        //            detaH += heightItemList[i];
        //        }
        //    }
        //    Rect svPos_temp = new Rect(new Vector2(0, r.y), new Vector2(position.width - wWith, position.height - r.y - detaH));
        //    Vector2 v = GetCententSize();

        //    svPos = GUI.BeginScrollView(new Rect(svPos_temp.x + wWith, svPos_temp.y + detaH, svPos_temp.width, svPos_temp.height), svPos, new Rect(r.x + wWith, r.y + detaH, v.x, v.y));
        //    //数据中两排后的数据
        //    DrawGridItem(r.position + new Vector2(wWith, wHeight), 4, heightItemList.Count); 

        //    GUI.EndScrollView();

        //    Debug.unityLogger.logEnabled = false;
        //    //顶部格子
        //    topGridSVPos = GUI.BeginScrollView(new Rect(svPos_temp.x, svPos_temp.y, svPos_temp.width + wWith, detaH), topGridSVPos, new Rect(r.x, r.y, v.x + wWith, detaH), false, false, "Label", "Label");
        //    topGridSVPos = new Vector2(svPos.x, topGridSVPos.y);
        //    Debug.unityLogger.logEnabled = true;
        //    //数据中的前两排格子
        //    DrawGridItem(r.position + new Vector2(wWith, wHeight), 0, 3);

        //    float tempWith = wWith;
        //    GUI.Label(new Rect(r.position, new Vector2(wWith, wHeight)), "", "SelectionRect");
        //    for (int i = 0; i < withItemList.Count; i++)
        //    {
        //        Rect dragR = new Rect(tempWith, r.y, withItemList[i], wHeight);
        //        Rect maxR = new Rect(tempWith, r.y, Screen.width * 5, wHeight);
        //        dragR = EditorDrawGUIUtility.DrawCanDragArea(dragR, maxR, null, EditorCanDragAreaSide.Right);
        //        if (dragR.width < minItem)
        //            dragR.width = minItem;
        //        withItemList[i] = dragR.width;

        //        tempWith += withItemList[i];

        //        if (GUI.Button(new Rect(dragR.position, new Vector2(dragR.width, dragR.height / 3)), "▼"))
        //        {
        //            if (selectColumnIndexs.Contains(i))
        //                selectColumnIndexs.Remove(i);
        //            else
        //                selectColumnIndexs.Add(i);
        //        }
        //        if (GUI.Button(new Rect(dragR.x, dragR.y + dragR.height / 3, dragR.width, dragR.height * 2 / 3), i.ToString()))
        //        {
        //            if (i == 0)
        //                continue;

        //            List<string> keys = new List<string>(m_currentData.fieldInfos.Keys);
        //            string key = keys[i];
        //            if (EditorUtility.DisplayDialog("警告", "是否删除字段[" + key + "]", "确定", "取消"))
        //            {
        //                m_currentData.DeleteField(key);
        //                withItemList.RemoveAt(i);
        //                return;
        //            }
        //        }

        //    }
        //    GUI.EndScrollView();

        //    //左边格子
        //    float tempHeight = r.y + wHeight;
        //    for (int i = 0; i < 2; i++)
        //    {
        //        Rect dragR = new Rect(r.x, tempHeight, wWith, heightItemList[i]);
        //        Rect maxR = new Rect(r.x, tempHeight, wWith, position.height);
        //        dragR = EditorDrawGUIUtility.DrawCanDragArea(dragR, maxR, null, EditorCanDragAreaSide.Bottom);
        //        if (dragR.height < minItem)
        //            dragR.height = minItem;
        //        heightItemList[i] = dragR.height;

        //        tempHeight += heightItemList[i];
        //        string vStr = "";
        //        if (i == 0)
        //        {
        //            vStr = "D";
        //            GUI.Label(dragR, vStr, buttonStyle);
        //        }
        //        else if (i == 1)
        //        {
        //            vStr = "description";
        //            GUI.Label(dragR, vStr, buttonStyle);
        //        }


        //    }
        //    //默认第一列
        //    Debug.unityLogger.logEnabled = false;
        //    leftGridSVPos = GUI.BeginScrollView(new Rect(svPos_temp.x, tempHeight, wWith, svPos_temp.height), leftGridSVPos, new Rect(r.x, tempHeight, wWith, v.y), false, false, "Label", "Label");
        //    leftGridSVPos = new Vector2(leftGridSVPos.x, svPos.y);
        //    Debug.unityLogger.logEnabled = true;

        //    for (int i = 2; i < heightItemList.Count; i++)
        //    {
        //        Rect dragR = new Rect(r.x, tempHeight, wWith, heightItemList[i]);
        //        Rect maxR = new Rect(r.x, tempHeight, wWith, position.height);
        //        dragR = EditorDrawGUIUtility.DrawCanDragArea(dragR, maxR, null, EditorCanDragAreaSide.Bottom);
        //        if (dragR.height < minItem)
        //            dragR.height = minItem;
        //        heightItemList[i] = dragR.height;

        //        tempHeight += heightItemList[i];
        //        string vStr = "";

        //        if (selectRowIndexs.Contains(i))
        //            GUI.color = Color.cyan;

        //        if (i == 2)
        //        {
        //            vStr = "default";
        //            GUI.Label(dragR, vStr, buttonStyle);
        //        }
        //        else
        //        {
        //            int num = i - 3;
        //            vStr = num.ToString();
        //            float firstLenth = dragR.width / 4;
        //            float threeQHeight = dragR.height / 3;
        //            if (GUI.Button(new Rect(dragR.position, new Vector2(firstLenth, dragR.height)), "►"))
        //            {
        //                if (selectRowIndexs.Contains(i))
        //                    selectRowIndexs.Remove(i);
        //                else
        //                    selectRowIndexs.Add(i);
        //            }
        //            if (GUI.Button(new Rect(dragR.x + firstLenth, dragR.y, firstLenth, threeQHeight), "▲"))
        //            {
        //                if (num > 0)
        //                    m_currentData.MoveLineData(num, num - 1);
        //            }
        //            if (GUI.Button(new Rect(dragR.x + firstLenth, dragR.y + threeQHeight, firstLenth, threeQHeight), "◍"))
        //            {
        //                GeneralDataModificationWindow.OpenWindow(editorWindow, "移动一行数据", num, (value) =>
        //                {
        //                    value = EditorDrawGUIUtil.DrawBaseValue("Index:", value);
        //                    GUILayout.Label("Current Index:" + num);
        //                    value = Mathf.Clamp((int)value, 0, m_currentData.datas.Count);

        //                    return value;
        //                },
        //                null,
        //        (value) =>
        //         {
        //             int index = (int)value;
        //             m_currentData.MoveLineData(num, index);

        //         });
        //                return;
        //            }
        //            if (GUI.Button(new Rect(dragR.x + firstLenth, dragR.y + threeQHeight * 2, firstLenth, threeQHeight), "▼"))
        //            {
        //                if (num < m_currentData.datas.Count - 1)
        //                    m_currentData.MoveLineData(num, num + 1);
        //            }
        //            if (GUI.Button(new Rect(dragR.x + firstLenth * 2, dragR.y, dragR.width - firstLenth * 2, dragR.height), vStr))
        //            {
        //                if (EditorUtility.DisplayDialog("警告", "是否删除第[" + num + "]行数据", "确定", "取消"))
        //                {
        //                    m_currentData.RemoveLineData(num);
        //                    heightItemList.RemoveAt(i);
        //                    return;
        //                }
        //            }
        //        }
        //        GUI.color = Color.white;

        //    }
        //    GUI.EndScrollView();
        //}

        //private Vector2 GetCententSize()
        //{
        //    float tempWith = 0;
        //    for (int i = 0; i < withItemList.Count; i++)
        //    {
        //        tempWith += withItemList[i];
        //    }
        //    tempWith += wWith;

        //    float tempHeight = 0;
        //    for (int i = 2; i < heightItemList.Count; i++)
        //    {

        //        tempHeight += heightItemList[i];
        //    }
        //    tempHeight += wHeight;
        //    return new Vector2(tempWith, tempHeight);
        //}

        private int oldButtonFontSize = 0;
        private int nowButtonFontSize = 0;
        private int MaxButtonFontSize = 40;

        private string searchValue = "";
        private void GridTopFunctionGUI()
        {
            GUILayout.Space(7);
            GUILayout.BeginHorizontal();

            m_currentData.description = EditorDrawGUIUtil.DrawBaseValue("表格描述", m_currentData.description).ToString();
            //字体大小调节
            helpBoxStyle.fontSize = 11;
            oldButtonFontSize = helpBoxStyle.fontSize;
            if (nowButtonFontSize <= 0)
            {
                nowButtonFontSize = PlayerPrefs.GetInt(FontPlayerPrefKey, oldButtonFontSize);
            }

            nowButtonFontSize = EditorGUILayout.IntSlider("字体大小", nowButtonFontSize, oldButtonFontSize / 2, MaxButtonFontSize);
            GUILayout.FlexibleSpace();
            //搜索
            searchValue = EditorDrawGUIUtil.DrawSearchField(searchValue, () =>
            {

            });
            GUILayout.EndHorizontal();
        }
        #region 默认菜单实现
        List<TableMenuBase> menuItems = new List<TableMenuBase>();

        private void InitCustomMenu()
        {
            menuItems.Clear();
           Type[] types= ReflectionUtils.GetChildTypes(typeof(TableMenuBase));
            foreach (var t in types)
            {
                object obj = Activator.CreateInstance(t);
                menuItems.Add((TableMenuBase)obj);
            }
        }
        private void AddGenericMenu()
        {
            var menu = new GenericMenu();

           
            menu.AddItem(new GUIContent("新建表格文件"), false, NewTableFile);
            menu.AddItem(new GUIContent("保存"), false, SaveTableFile);
            menu.AddItem(new GUIContent("加载上次保存"), false, ReloadTableFile);
            menu.AddSeparator("");

            menu.AddItem(new GUIContent("添加一行数据"), false, AddLineDataGUI);
            menu.AddItem(new GUIContent("添加字段"), false, Add2FieldGUI);
            menu.AddSeparator("");
            foreach (var item in menuItems)
            {
                if (item.CanOpen(this))
                {
                    menu.AddItem(new GUIContent(item.MenuName), false, (obj) => {
                        TableDataEditor tableData = (TableDataEditor)obj;
                        item.Excute(tableData);
                        AssetDatabase.Refresh();
                    }, this);
                }
                else
                {
                    menu.AddDisabledItem(new GUIContent(item.MenuName), false);
                }
          
            }
            menu.AddSeparator("");
            menu.AddSeparator("");
            menu.AddItem(new GUIContent("删除表格"), false, DeleteTableFile);

            menu.ShowAsContext();
        }

        /// <summary>
        /// 添加一个字段
        /// </summary>
        private void Add2FieldGUI()
        {
            GeneralDataModificationWindow.OpenWindow(editorWindow, "添加字段", new TableFieldInfo(), (value) =>
            {
                TableFieldInfo info = (TableFieldInfo)value;
                DrawTableConfigFieldInfo(info);

                if (string.IsNullOrEmpty(info.name))
                    EditorGUILayout.HelpBox("字段名不能为空！！", MessageType.Error);
                else if (info.name.Contains(" "))
                    EditorGUILayout.HelpBox("字段名不能有空格！！", MessageType.Error);
                else if (m_currentData.fieldInfos.ContainsKey(info.name))
                    EditorGUILayout.HelpBox("字段名重复！！", MessageType.Error);
                return value;
            },
            (value) =>
            {
                TableFieldInfo info = (TableFieldInfo)value;
                if (string.IsNullOrEmpty(info.name) || m_currentData.fieldInfos.ContainsKey(info.name) || info.name.Contains(" "))
                    return false;
                return true;

            },
            (value) =>
            {
                TableFieldInfo info = (TableFieldInfo)value;
                m_currentData.AddField(info, m_currentData.fieldInfos.Count);
              gridData.AddColumn();
            });
        }


        /// <summary>
        /// 添加一行数据
        /// </summary>
        private void AddLineDataGUI()
        {
            GeneralDataModificationWindow.otherParameter = m_currentData.datas.Count;
            GeneralDataModificationWindow.OpenWindow(editorWindow, "插入一行数据", "", (value) =>
            {
                value = EditorDrawGUIUtil.DrawBaseValue("Key:", value);
                GeneralDataModificationWindow.otherParameter = EditorDrawGUIUtil.DrawBaseValue("Insert Index:", GeneralDataModificationWindow.otherParameter);
                GeneralDataModificationWindow.otherParameter = Mathf.Clamp((int)GeneralDataModificationWindow.otherParameter, 0, m_currentData.datas.Count);
                string key = value.ToString();
                if (string.IsNullOrEmpty(key))
                    EditorGUILayout.HelpBox("Key不能为空！！", MessageType.Error);
                else if (key.Contains(" "))
                    EditorGUILayout.HelpBox("Key 不能有空格！！", MessageType.Error);
                else if (m_currentData.datas.ContainsKey(key.Trim()))
                    EditorGUILayout.HelpBox("Key重复！！", MessageType.Error);
                return value;
            },
             (value) =>
             {
                 string key = value.ToString();
                 if (string.IsNullOrEmpty(key) || (key.Contains(" ")) || m_currentData.datas.ContainsKey(key.Trim()))
                     return false;

                 return true;

             },
           (value) =>
           {
               int index = (int)GeneralDataModificationWindow.otherParameter;
               string key = value.ToString();
               gridData.AddRow();
               m_currentData.AddLineData(index, key);

           });


        }
        private void DeleteTableFile()
        {
            if (EditorUtility.DisplayDialog("警告", "是否删除文件[" + chooseFileName + "]", "确定", "取消"))
            {
                File.Delete(TableDefine.SaveConfigFilePath + "/" + chooseFileName + ".txt");
                AssetDatabase.Refresh();
                chooseFileName = "";
                ReInit();
                return;
            }
        }
        private void ReloadTableFile()
        {
            LoadData(chooseFileName);
        }
        private void SaveTableFile()
        {
            SaveData(chooseFileName, m_currentData);
        }
       private void NewTableFile()
        {
            GeneralDataModificationWindow.otherParameter = "";
            GeneralDataModificationWindow.OpenWindow(editorWindow, "新建配置文件", "", (value) =>
            {
                value = EditorDrawGUIUtil.DrawBaseValue("新建配置文件:", value);
                GeneralDataModificationWindow.otherParameter = EditorDrawGUIUtil.DrawBaseValue("主键名:", GeneralDataModificationWindow.otherParameter);
                string fileName = value.ToString();
                string key = GeneralDataModificationWindow.otherParameter.ToString();
                if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(key))
                {
                    EditorGUILayout.HelpBox("文件名或主键名不能为空！！", MessageType.Error);
                }
                else if ((key.Contains(" ")) || (fileName.Contains(" ")))
                    EditorGUILayout.HelpBox("文件名或主键名有空格！！", MessageType.Error);
                else if (configFileNames.Contains(fileName))
                {
                    EditorGUILayout.HelpBox("文件名重复！！", MessageType.Error);
                }

                return value;
            },
            (value) =>
            {
                string fileName = value.ToString();
                string key = GeneralDataModificationWindow.otherParameter.ToString();
                if (string.IsNullOrEmpty(fileName)
                || string.IsNullOrEmpty(key)
                || (key.Contains(" ")) || (fileName.Contains(" "))
                || configFileNames.Contains(fileName))
                {
                    return false;
                }
                else
                    return true;

            },
            (value) =>
            {
                TableData data = new TableData();
                string keyName = GeneralDataModificationWindow.otherParameter.ToString();
                chooseFileName = value.ToString();

                TableFieldInfo info = new TableFieldInfo();
                info.name = keyName;
                info.fieldType =typeof(string);
                info.description = "Key";
                info.defultValue = "";
                data.AddField(info, 0);
                resetChooseFileName = chooseFileName;
                SaveData(chooseFileName, data);
                ReInit();
            });
        }
        #endregion
        ///// <summary>
        ///// 绘制每个数据格子
        ///// </summary>
        ///// <param name="startPos"></param>
        //private void DrawGridItem(Vector2 startPos, int heightStartIndex, int heightEndIndex)
        //{
        //    helpBoxStyle.fontSize = nowButtonFontSize;
        //    float tempHeight = 0;
        //    for (int i = 0; i < heightStartIndex; i++)
        //    {
        //        tempHeight += heightItemList[i];
        //    }
        //    List<TableFieldInfo> fieldInfos = new List<TableFieldInfo>(m_currentData.fieldInfos.Values);
        //    List<string> keys = new List<string>(m_currentData.datas.Keys);

        //    for (int i = heightStartIndex; i < heightEndIndex; i++)
        //    {
        //        float h = heightItemList[i];
        //        float tempWith = 0;


        //        for (int j = 0; j < withItemList.Count; j++)
        //        {
        //            float w = withItemList[j];

        //            Vector2 size = new Vector2(w, h);
        //            Vector2 pos = startPos + new Vector2(tempWith, tempHeight);

        //            object value = null;
        //            string showStr = "";

        //            TableFieldInfo info = fieldInfos[j];
        //            string field = info.name;

        //            if (i == 0)
        //            {
        //                GUI.color = Color.yellow;

        //                showStr = EditorDrawGUIUtil.GetFormatName(field, TableUtils.TableFieldType2Type(info.fieldType, info.enumType), "red");
        //            }
        //            else if (i == 1)
        //            {
        //                GUI.color = Color.cyan;

        //                showStr = info.description;
        //            }
        //            else if (i == 2)
        //            {
        //                GUI.color = Color.green;

        //                showStr = TableUtils.ObjectValue2TableString(info.defultValue);
        //            }
        //            else
        //            {
        //                string k = keys[i - 3];
        //                Dictionary<string, object> values = m_currentData.datas[k];
        //                value = values[info.name];

        //                bool isDefault = TableUtils.ValueEquals(info.defultValue, value);

        //                if (isDefault)
        //                {
        //                    showStr = TableUtils.ObjectValue2TableString(info.defultValue);
        //                }
        //                else
        //                {
        //                    showStr = TableUtils.ObjectValue2TableString(value);
        //                }
        //                if (!string.IsNullOrEmpty(searchValue))
        //                    showStr = ShowContainsChar(showStr, searchValue);

        //                if (isDefault)
        //                    showStr = "<color=green>" + showStr + "</color>";
        //            }

        //            if (i == 0||i == 1 || i == 2)
        //            {
        //                GUI.Button(new Rect(pos, size), showStr, helpBoxStyle);
        //            }
        //            else
        //            {
        //                if (selectColumnIndexs.Contains(j))
        //                    GUI.color = Color.magenta;
        //                if (selectRowIndexs.Contains(i))
        //                    GUI.color = Color.cyan;
        //                if (GUI.Button(new Rect(pos, size), showStr, helpBoxStyle))
        //                {
        //                    modifiIndex = new Vector2Int(i - 3, j);
        //                    if (i == 0)
        //                    {
        //                        value = info.Clone();
        //                    }
        //                    else
        //                    {
        //                        Type t = TableUtils.TableFieldType2Type(info.fieldType, info.enumType);
        //                        string tempJson = JsonUtils.ToJson(value);
        //                        value = JsonUtils.FromJson(t, tempJson);
        //                    }

        //                    GeneralDataModificationWindow.OpenWindow(editorWindow, "修改数据", value, DrawModifiValueGUI, CheckModifiValueCallBack, ModificationCompleteCallBack);
        //                }
        //            }
        //            GUI.color = Color.white;
        //            tempWith += w;
        //        }

        //        tempHeight += h;
        //    }
        //    helpBoxStyle.fontSize = oldButtonFontSize;
        //}
        private string ShowContainsChar(string value, string searchValue)
        {
            string res = value;
            if (value.Contains(searchValue))
            {
                res = value.Replace(searchValue, "<color=red>" + searchValue + "</color>");
            }

            return res;
        }

        /// <summary>
        /// 绘制数据修改窗口
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        private object DrawModifiValueGUI(object t)
        {
            List<TableFieldInfo> fieldInfos = new List<TableFieldInfo>(m_currentData.fieldInfos.Values);
            TableFieldInfo info = fieldInfos[modifiIndex.y];
            if (t is TableFieldInfo)
            {
                TableFieldInfo tempInfo = (TableFieldInfo)t;
                DrawTableConfigFieldInfo(tempInfo);
                if (string.IsNullOrEmpty(info.name))
                {
                    EditorGUILayout.HelpBox("字段名不能为空！！", MessageType.Error);
                }
                else if (CheckIsNameRepeat(tempInfo))
                    EditorGUILayout.HelpBox("字段名不能重复！！", MessageType.Error);
            }
            else
            {

                EditorDrawGUIUtil.CanEdit = false;
                EditorDrawGUIUtil.DrawBaseValue("字段名", info.name);
                EditorDrawGUIUtil.CanEdit = true;
                GUILayout.Space(7);
                GUILayout.Label("字段描述：" + info.description);


                GUILayout.BeginHorizontal();
                EditorDrawGUIUtil.CanEdit = false;
                EditorDrawGUIUtil.DrawBaseValue("默认值", info.defultValue);
                EditorDrawGUIUtil.CanEdit = true;
                GUILayout.FlexibleSpace();

                if (GUILayout.Button("默认值", GUILayout.Width(60)))
                {
                    t = info.defultValue;
                }
                GUILayout.EndHorizontal();

                TableDataDrawFieldBase dataDrawObject = TableDataDrawFieldController.GetTableDataDrawField(info.fieldType, info.tag);
                t = dataDrawObject.DrawGUI("值", t, info);
            }

            return t;
        }
        private bool CheckModifiValueCallBack(object t)
        {
            if (t is TableFieldInfo)
            {
                TableFieldInfo info = (TableFieldInfo)t;

                if (string.IsNullOrEmpty(info.name))
                    return false;

                if (CheckIsNameRepeat(info))
                    return false;

                if (info.defultValue == null)
                    return false;

            }

            return true;
        }
        private bool CheckIsNameRepeat(TableFieldInfo info)
        {
            List<TableFieldInfo> fieldInfos = new List<TableFieldInfo>(m_currentData.fieldInfos.Values);
            TableFieldInfo oldInfo = fieldInfos[modifiIndex.y];
            List<string> names = new List<string>(m_currentData.fieldInfos.Keys);
            names.Remove(oldInfo.name);

            return names.Contains(info.name);
        }

        string typeFullName = "";
        /// <summary>
        /// 绘制字段信息
        /// </summary>
        /// <param name="info"></param>
        private void DrawTableConfigFieldInfo(TableFieldInfo info)
        {
            Type type = info.fieldType;// TableUtils.TableFieldType2Type(info.fieldType, info.enumType);
            if (type != null && (info.defultValue == null || type != info.defultValue.GetType()))
                info.defultValue = ReflectionUtils.CreateDefultInstance(type);

            //是否使用多语言字段


            GUILayout.BeginVertical("box");

            GUILayout.EndVertical();
            info = (TableFieldInfo)EditorDrawGUIUtil.DrawClassData("字段信息", info, new List<string>() { "tag", "defultValue", "fieldType" }, null, () =>
            {
              
                if (type != null)
                {
                    TableTypeData typeData = TableTypeSupportController.Instance.GetTypeData(type, info.tag);
                    typeFullName = typeData.dataType;
                }
                Type changeType = null;
                List<string> types = new List<string>(TableTypeData.CommonTableTypeData.Keys);
                if(string.IsNullOrEmpty(typeFullName)|| types.Contains(typeFullName))
                {
                    typeFullName = EditorDrawGUIUtil.DrawPopup("类型", typeFullName, types, null);
                    
                   
                }
                typeFullName = EditorDrawGUIUtil.DrawBaseValue("类型", typeFullName).ToString();
                if (TableTypeData.CommonTableTypeData.ContainsKey(typeFullName))
                    changeType = TableTypeSupportController.Instance.GetTableType(TableTypeData.CommonTableTypeData[typeFullName]);
                else
                {
                    changeType =ReflectionUtils.GetTypeByTypeFullName(typeFullName,false);
                }
                if (changeType == null|| !TableTypeSupportController.Instance.IsSupportType(changeType))
                {
                    EditorGUILayout.HelpBox("字段类型错误！！", MessageType.Error);
                }
                else
                {
                    info.fieldType = changeType;
                }
                //if (info.fieldType.IsEnum)
                //{
                //    info.enumType = EditorDrawGUIUtil.DrawBaseValue("枚举类型", info.enumType).ToString(); ;
                //    if (type == null)
                //    {
                //        EditorGUILayout.HelpBox("不存在的枚举类型！！", MessageType.Error);
                //    }
                //}
                List<string> tags = TableDataDrawFieldController.GetTags(info.fieldType);

                if (string.IsNullOrEmpty(info.tag))
                    info.tag = TableDataDrawFieldController.DefaultTag;
                info.tag = EditorDrawGUIUtil.DrawPopup("Tag", info.tag, tags);
                if (info.tag == TableDataDrawFieldController.DefaultTag)
                    info.tag = "";


                TableDataDrawFieldBase dataDrawObject = TableDataDrawFieldController.GetTableDataDrawField(info.fieldType, info.tag);
                info.defultValue = dataDrawObject.DrawGUI("默认值", info.defultValue, info);

            });
        }

        private Vector2Int modifiIndex = new Vector2Int();
        /// <summary>
        /// 修改格子数据完成回调
        /// </summary>
        /// <param name="t"></param>
        private void ModificationCompleteCallBack(object t)
        {
            List<TableFieldInfo> fieldInfos = new List<TableFieldInfo>(m_currentData.fieldInfos.Values);
            TableFieldInfo oldInfo = fieldInfos[modifiIndex.y];

            if (t is TableFieldInfo)
            {
                //修改数据
                TableFieldInfo info = (TableFieldInfo)t;
                if (info.name != oldInfo.name)
                {
                    m_currentData.RenameField(oldInfo.name, info.name);
                }
                m_currentData.ChangeFieldType(info.name, info.fieldType, info.defultValue);

                oldInfo.description = info.description;
                oldInfo.tag = info.tag;
            }
            else
            {

                List<Dictionary<string, object>> values = new List<Dictionary<string, object>>(m_currentData.datas.Values);
                Dictionary<string, object> v = values[modifiIndex.x];

                v[oldInfo.name] = t;
            }
        }

        #endregion
        #region 保存数据
        public  void SaveData(string fileName, TableData data)
        {
            OnSaveTableData(fileName, data);
           
            UnityEditor.AssetDatabase.Refresh();
            OnClearModuleCache();
            //TableManager.ReleaseAll();
            // ResourceManager.ReleaseAll();
        }

        #endregion
    }
}


